/************************************************************
*  * HONGHE CONFIDENTIAL
* __________________
* Copyright (C) 2014-2015 HONGHE Technologies. All rights reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of HONGHE Technologies.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from HONGHE Technologies.
* The author is knight(卢远强), ios software engineer.
*/

import UIKit
import MediaPlayer
class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,HttpProtocol,ChannelProtocol{
    @IBOutlet var tap: UITapGestureRecognizer!=nil
    
     @IBOutlet var btnPlay: UIImageView!
    
    @IBOutlet var tv: UIImageView!
    @IBOutlet weak var bigImg: UIImageView!

    @IBOutlet weak var TV: UITableView!
    @IBOutlet weak var progressView: UIProgressView!
    @IBOutlet weak var playTimer: UILabel!
    @IBOutlet var ontap: UITapGestureRecognizer!=nil
    var eHttp: HttpController = HttpController()
    @IBAction func Ontap(sender: UITapGestureRecognizer) {
        
        if sender.view==btnPlay{
        btnPlay.hidden=true
            autoPlay.play()
        btnPlay.removeGestureRecognizer(ontap)
           tv.addGestureRecognizer(ontap)
        }else if sender.view==tv{
            btnPlay.hidden=false
            autoPlay.pause()
               tv.removeGestureRecognizer(ontap)
            btnPlay.addGestureRecognizer(ontap)
        }
    }
    var timer:NSTimer = NSTimer()
    var tableData:NSArray = NSArray()
    var channelData: NSArray = NSArray()
    var imageCache = Dictionary<String ,UIImage>()
    var autoPlay:MPMoviePlayerController = MPMoviePlayerController()
    override func viewDidLoad()
    {
        super.viewDidLoad()
        eHttp.delegate=self
      //  chnnels.delegate=self
        eHttp.onSearch("http://www.douban.com/j/app/radio/channels")
        eHttp.onSearch("http://douban.fm/j/mine/playlist?channel=0")
        progressView.progress=0.0
       tv.addGestureRecognizer(ontap)
    }

     func onChnnel(channels_ur: String) {
        var answer2 = channels_ur.toInt()
       var url:String="http://douban.fm/j/mine/playlist?channel=\(channels_ur)"
       // var urls:String="http://douban.fm/j/mine/playlist?2)"
        eHttp.onSearch(url)
      //self.TV .reloadData()
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return tableData.count
    }
    func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        cell.layer.transform=CATransform3DMakeScale(0.1, 0.1, 1)
        UIView .animateWithDuration(0.25, animations: { () -> Void in
            cell.layer.transform=CATransform3DMakeScale(1, 1, 1)
        })
        
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell=UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "douban")
        let rowData: NSDictionary=tableData[indexPath.row] as! NSDictionary
        cell.textLabel?.text=rowData["title"] as? String
        cell.detailTextLabel?.text=(rowData["artist"] as! String)
        cell.imageView?.image=UIImage(named: "detail.jpg")
        let url=rowData["picture"] as! String
        let image=imageCache[url]
        if !(image != nil)
        {
            let imgURL:NSURL=NSURL(string: url)!
            let request:NSURLRequest=NSURLRequest(URL:imgURL)
            NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(Response:NSURLResponse!, data:NSData!, error:NSError!) -> Void in
                let img=UIImage(data: data)
                cell.imageView?.image=img
                self.imageCache[url]=img
            })
        }else{
         cell.imageView?.image=image
        }
        return cell
    }
     func didRecivevResult(result: NSDictionary) {
        if (result["song"] != nil) {
        self.tableData=result["song"] as! NSArray
            self.TV .reloadData()
            let fireDic:NSDictionary=self.tableData[0] as! NSDictionary
            let uris=fireDic["picture"] as! String
            onSetImage(uris)
            let bguri=fireDic["url"] as! String
            onSetAutdio(bguri)
        }else if ((result["channels"]) != nil){
        self.channelData=result["channels"] as! NSArray
            self.TV .reloadData()
           
        }
    }
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let row:NSDictionary=self.tableData[indexPath.row] as! NSDictionary
        let uri=row["url"] as! String
          let uripicture=row["picture"] as! String
        onSetAutdio(uri)
        onSetImage(uripicture)
    }
    func onSetAutdio(uri:String){
        self.timer.invalidate()
        playTimer.text="00:00"
        
    self.autoPlay.stop()
    self.autoPlay.contentURL=NSURL(string: uri)
    self.autoPlay.play()
        timer=NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "onUpdata", userInfo: nil, repeats: true)
        btnPlay .removeGestureRecognizer(ontap)
        tv .addGestureRecognizer(ontap)
        btnPlay.hidden=true
    }
    func onUpdata(){
    let c=self.autoPlay.currentPlaybackTime
        if c>0.0 {
            let t=autoPlay.duration
            let p:CFloat=CFloat(c/t)
            progressView.setProgress(p, animated: true)
            let all:Int=Int(c)
            let m:Int=all%60
            let f:Int=Int(all/60)
            var time:String=""
            //var timem:String=""
            if f<10 {
                time="0\(f):"
            }else{
                time="\(f):"
            }
            if m<10 {
             time+="0\(m)"
            }else{
             time+="\(m)"
            }
            playTimer.text=time
        }
     
    }
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
            let viewct:ChannelController = segue.destinationViewController as! ChannelController
        viewct.delegate=self
            viewct.channelData=self.channelData
    }
    func onSetImage(uri:String)
    {
     let image=imageCache[uri]
        if !(image != nil)
        {
         let imgURL=NSURL(string: uri)
          let request:NSURLRequest=NSURLRequest(URL: imgURL!)
            NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: { (response:NSURLResponse!, data:NSData!, error:NSError!) -> Void in
               let img=UIImage(data: data)
                 self.bigImg.image=img
                self.imageCache[uri]=img
          })
        }else{
         self.bigImg.image=image
        }
        
    }

}

